package com.gan.simple_init.common.filter;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.gan.simple_init.common.base.ResponseErrorEnum;
import com.gan.simple_init.common.base.RestResultGenerator;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义用户权限不足处理类
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletRequest.setCharacterEncoding("UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();

        writer.write(new ObjectMapper().writeValueAsString(RestResultGenerator.error(ResponseErrorEnum.USER_NO_PERMISSION)));
        writer.flush();
        writer.close();
    }
}
